﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExpressionEngine;
using ExpressionEngine.ValueProviders;

namespace AspNetGridViewExpressionSummary
{
    public partial class Default : System.Web.UI.Page
    {
        AggregateExpressionEvaluator summary1 = new AggregateExpressionEvaluator("SUM(Column1)");
        AggregateExpressionEvaluator summary2 = new AggregateExpressionEvaluator("(SUM(Column3)-SUM(Column2))/COUNT()");
        AggregateExpressionEvaluator summary3 = new AggregateExpressionEvaluator("SUM((Column3 + Column2)/2)");
        AggregateExpressionEvaluator summary4 = new AggregateExpressionEvaluator("AVG(Column4/Column3)");
        AggregateExpressionEvaluator summary5 = new AggregateExpressionEvaluator("MIN(Column5+1)+2");
        AggregateExpressionEvaluator summary6 = new AggregateExpressionEvaluator("MAX(Column6-1)-2");
        
        protected void Page_Load(object sender, EventArgs e)
        {
            gvExpressionSummary.DataSource = DemoData.Generate();

            if (!IsPostBack)
            {
                gvExpressionSummary.DataBind();
            }
        }

        protected void gvExpressionSummary_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ReflectionValueProvider provider = new ReflectionValueProvider(e.Row.DataItem);

                summary1.RowChanged(provider);
                summary2.RowChanged(provider);
                summary3.RowChanged(provider);
                summary4.RowChanged(provider);
                summary5.RowChanged(provider);
                summary6.RowChanged(provider);
            }
            
            if(e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[0].Text = string.Format("SUM(Column1) = {0}", summary1.GetResult());
                e.Row.Cells[1].Text = string.Format("(SUM(Column3)-SUM(Column2))/COUNT() = {0}", summary2.GetResult());
                e.Row.Cells[2].Text = string.Format("SUM((Column3 + Column2)/2) = {0}", summary3.GetResult());
                e.Row.Cells[3].Text = string.Format("AVG(Column4/Column3) = {0}", summary4.GetResult());
                e.Row.Cells[4].Text = string.Format("MIN(Column5+1)+2 = {0}", summary5.GetResult());
                e.Row.Cells[5].Text = string.Format("MAX(Column6-1)-2 = {0}", summary6.GetResult());
            }
        }
    }
}